
define(['jquery', 'd3','util','hammer'], function($, d3,util,Hammer) {
	function rectChart(url) {
		var setting = {
			selector: '#night',
			margin: {
				top: 30,
				left: 5,
				bottom: 20,
				right: 45
			},
			rectStyle: {
				'fill': '#8ac5fc'
			},
			pathStyle: {
				'fill': 'none',
				'stroke': '#ffc10e',
				'stroke-width': '2px'
			},

			series: null

		}
		rectChart(setting)

		function rectChart(setting) {

			d3.json(url, function(dataset) {

				var dataLength = dataset.data.length
				setting.series = dataset.data

				for (var i=0;i<dataLength;i++) {
					setting.series[i].name = setting.series[i].mytime
					setting.series[i].value = setting.series[i].avgTeamCommission
				}

				var width, height, selector,
					colorset, dom, position,
					name, value, i, serie,
					data, min, max, xScale,
					yScale, xScaleData, margin,
					contentW, contentH, xAxis, yAxis,
					valueLine, linearGradient, event, line,
					hightCircle, lowCircle

				var svg, content, left, right, ticks,
					lineWrap, total = [],
					income = []


				selector = setting.selector
				dom = document.querySelector(selector)
				dom1 = document.querySelector(selector+ " div")
				position = dom.getBoundingClientRect()
				position1 = dom1.getBoundingClientRect()
				var YrelcontentW = position.width
				var relcontentW = position1.width
				height = position.height
				colorset = setting.colorset
				data = setting['series']
				margin = setting['margin']

				var num = []


				min = d3.min(data, function(d, i) {

					return d.value
				})
				max = d3.max(data, function(d, i) {


					return d.value
				})

				max = Math.ceil(max / 100) * 100

				var format = d3.time.format("%Y-%m")
				xScaleData = []

				var screenWidth = document.documentElement.clientWidth
				if (screenWidth == 375) {
					var rectWidth = 26
					var realWidth = data.length * rectWidth
				} else if (screenWidth > 375) {
					var rectWidth = 29
					var realWidth = data.length * rectWidth
				} else {
					var rectWidth = 21.5
					var realWidth = data.length *rectWidth
				}
				if (data.length > 12) {
					data.forEach(function(d, i) {

						xScaleData.push(format.parse(d.name))
					})


					var width = xScaleData.length * 0.1 * YrelcontentW
					contentW = width - margin.left - margin.right
					contentH = height - margin.top - margin.bottom

					xScale = d3.time.scale()
						.domain(d3.extent(xScaleData))
						.range([0, contentW])

				} else if (data.length <= 12) {
					data.forEach(function(d, i) {
						if (i == 0) {
							xScaleData.push(d.name.slice(0,4))
						} else {
							xScaleData.push(d.name.slice(5))
						}

					})

					var width = YrelcontentW

					contentW = width - margin.left - margin.right

					contentH = height - margin.top - margin.bottom

					xScale = d3.scale.ordinal()
						.domain(xScaleData)
						.rangeBands([0, realWidth], 0)
				}
				var translate = (contentW / xScaleData.length) / 2


				xAxis = d3.svg.axis()
					.scale(xScale)
					.orient('bottom')
					.tickValues(xScaleData)
					.tickSize(-contentH)

				svg = d3.select(selector + " div")
					.append('svg')
					.attr('width', width)
					.attr('height', height)
					.attr("class", "rect_bar")

				var Ysvg = d3.select(selector)
					.append('svg')
					.attr('width', YrelcontentW)
					.attr('height', height)

				svg.append('g')
					.attr('class', 'axis')
					.classed('xAxis', true)
					.attr('transform', 'translate(' + margin.left + ',' + (margin.top + contentH) + ')')
					.call(xAxis)
				svg.append('line')
					.attr('x1', margin.left)
					.attr("y1", margin.top)
					.attr("x2", width)
					.attr("y2", margin.top)
					.attr("fill", "none")
					.attr("stroke", "#F3F3F4")
					.attr("stroke-width", "2px")

				svg.append('line')
					.attr('x1', margin.left)
					.attr("y1", margin.top + contentH)
					.attr("x2", width)
					.attr("y2", margin.top + contentH)
					.attr("fill", "none")
					.attr("stroke", "#F3F3F4")
					.attr("stroke-width", "2px")
				// svg.append('g')
				// 	.attr('class', 'axis')
				// 	.classed('xAxis', true)
				// 	.classed('hidden', true)
				// 	.attr('transform', 'translate(' + margin.left + ',' + (margin.top) + ')')
				// 	.call(xAxis.tickSize(0).tickValues(null))

				for (var j = 0; j < xScaleData.length; j++) {

					d3.select(svg.selectAll('.xAxis text')[j])
						.text(function() {
							for (var i = 0; i < xScaleData.length; i++) {
								if (data.length > 12) {
									$(this[i]).attr("x", translate)
								} else {
									svg.select(".xAxis").selectAll("g line")
										.attr("x2",-(rectWidth/2))
										.attr("x1",-(rectWidth/2))
								}


								$(this[i]).attr("class", function() {
									return "rect" + i
								})
								$(this[i]).attr("data", function() {
									return i
								})
								if (d3.select(this[i]).text() == "February") {
									d3.select(this[i]).text(2)
								} else if (d3.select(this[i]).text() == "March") {
									d3.select(this[i]).text(3)
								} else if (d3.select(this[i]).text() == "April") {
									d3.select(this[i]).text(4)
								} else if (d3.select(this[i]).text() == "May") {
									d3.select(this[i]).text(5)
								} else if (d3.select(this[i]).text() == "June") {
									d3.select(this[i]).text(6)
								} else if (d3.select(this[i]).text() == "July") {
									d3.select(this[i]).text(7)
								} else if (d3.select(this[i]).text() == "August") {
									d3.select(this[i]).text(8)
								} else if (d3.select(this[i]).text() == "September") {
									d3.select(this[i]).text(9)
								} else if (d3.select(this[i]).text() == "October") {
									d3.select(this[i]).text(10)
								} else if (d3.select(this[i]).text() == "November") {
									d3.select(this[i]).text(11)
								} else if (d3.select(this[i]).text() == "December") {
									d3.select(this[i]).text(12)
								}
							}
						})

				}



				yScale = d3.scale.linear()
					.domain([max, 0])
					.range([0, contentH])

				yAxis = d3.svg.axis()
					.scale(yScale)
					.orient('right')
					.tickSize(0)
				Ysvg.append('g')
					.attr('class', 'axis')
					.classed('yAxis', true)
					.attr('transform', 'translate(' + (YrelcontentW - margin.right) + ',' + margin.top + ')')
					.call(yAxis)

				content = svg.append('g')
					.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

				linearGradient = content.append('defs')
					.append('linearGradient')
					.attr('id', 'mylinearGradient')
					.attr('x1', '0%')
					.attr('y1', ' 0%')
					.attr('x2', '0%')
					.attr('y2', '100%')

				linearGradient.append('stop')
					.attr('offset', '50%')
					.attr('stop-color', setting.rectStyle.fill)
					.attr('stop-opacity', '1')

				linearGradient.append('stop')
					.attr('offset', '100%')
					.attr('stop-color', '#fff')
					.attr('stop-opacity', '1')

				content.append('g').selectAll('rect')
					.data(data)
					.enter()
					.append('rect')
					.attr('x', function(d, i) {

						return xScale(xScaleData[i])
					})
					.attr('y', function(d, i) {
						return yScale(d.value)
					})
					.attr('width', 0)
					.attr('height', function(d, i) {

						return contentH - yScale(d.value)
					})
					.style(setting.rectStyle)
					.style('fill', 'url(#mylinearGradient)')
					.on('click', touch)
					.transition()
					.duration(2000)
					.attr('width',function(d,i) {
						if (data.length>12) {
							return (contentW/xScaleData.length -1)
						} else {
							return rectWidth-1
						}
					})
					.attr("data", function(d, i) {

						return i
					})



				lineWrap = content.append('g')
					.style('display', 'none')



				var rect = lineWrap.append("g")

				rect.append("rect")
					.attr("width", 40)
					.attr("height", 20)
					.attr("fill", '#ffc30e')
				rect.append("polygon")
					.attr("points", function(d, i) {
						return 0 + "," + 5 + " " + 40 + "," + 5 + " " + 20 + "," + 27
					})
					.attr("fill", "#ffc30e")
				// .attr("transform", "translate(" + margin.left + "," + (-26) + ")")
				// .attr("stroke", function(d, i) {
				// 	return colorset[i]
				// })
				// .attr("stroke-width", 1)
				rect.append("text")
					.attr("transform", "translate(" + 20 + "," + 18 + ")")
					.style("fill", "#000")
					.style("font-size", "16px")
					.attr('text-anchor', 'middle')
					.attr("class", "rectClass")
					.text("111")



				line = lineWrap.append('line')
					.attr('x1', 0)
					.attr('y1', 0)
					.attr('x2', 0)
					.attr('y2', contentH)
					.style(setting.pathStyle)


				lowCircle = lineWrap.append('circle')
					.attr('r', 6)
					.attr('fill', setting.pathStyle.stroke)
					.attr('stroke-width', '2px')
					.attr('stroke', '#fff')
				// hightCircle = lineWrap.append('g')

				// hightCircle.append('circle')
				// 	.attr('r', 10)
				// 	.attr('fill', '#fff')
				// 	.attr('stroke-width', '2px')
				// 	.attr('stroke', setting.pathStyle.stroke)

				// hightCircle.append('circle')
				// 	.attr('r', 6)
				// 	.attr('fill', setting.pathStyle.stroke)



				svg.selectAll(".xAxis text")
					.on('click', touch)
				//.on('touchmove', touch)


				// .on('touchend', function(d) {
				// 	line
				// 		.style('display', 'none')
				// })

				var hammertime = new Hammer(document.querySelector(".rect_bar"));
				//添加事件
				var cur = 0

				var ulWidth = width

				var two_3 = $("#night_1").width()



				hammertime.on("pan", function(e) {
					if (data.length <= 12) {
						return
					}

					cur += e.deltaX;

					if (cur * 0.2 > 0) {
						cur = 0;
						$(".rect_bar").css("margin-left", 0)

						return
					}
					if (cur * 0.2 < -ulWidth + two_3) {
						cur = (-ulWidth + two_3) / 0.2

						$(".rect_bar").css("margin-left", -ulWidth + two_3 + margin.left)

						return
					}

					$(".rect_bar").css("margin-left", cur * 0.2)
				})

				function end(line) {
					line.transition()
						.duration(3000)
						.attrTween("stroke-dasharray", tweenDash)
						.attr('fill-opacity', 1)

				}

				function tweenDash() {
					var l = this.getTotalLength(),
						i = d3.interpolateString("0,kkk" + l, l + "," + l);
					return function(t) {
						return i(t);
					}
				}

				function touch() {



					var index1 = d3.select(this).attr("data")

					console.log(index1)
					num = []
					var target = null,
						tagName, height,
						position, left, key,
						lineValue, rectValue,
						index, arr

					position = d3.mouse(dom)
					target = d3.event.target
					tagName = target.tagName


					left = position[0] - margin.left - parseInt($(".rect_bar").css("margin-left"))

					arr = getData(left)

					index = arr[0]

					if (index >= 0) {

						lineWrap.style('display', 'block')

						rect.select(".rectClass").text(data[index1].value.toFixed(0))
						if (data.length >12) {
							rect.attr('transform', 'translate(' + (xScale(xScaleData[index1]) + (contentW / xScaleData.length / 2) - 20) + ',' + -28 + ')')

							line
								.attr('transform', 'translate(' + (xScale(xScaleData[index1]) + (contentW / xScaleData.length / 2)) + ',' + 0 + ')')

							lowCircle
								.attr('transform', 'translate(' + (xScale(xScaleData[index1]) + (contentW / xScaleData.length / 2)) + ',' + yScale(data[index1].value) + ')')
						} else {
							rect.attr('transform', 'translate(' + (xScale(xScaleData[index1]) + (rectWidth / 2) - 20) + ',' + -28 + ')')

							line
								.attr('transform', 'translate(' + (xScale(xScaleData[index1]) + (rectWidth / 2)) + ',' + 0 + ')')

							lowCircle
								.attr('transform', 'translate(' + (xScale(xScaleData[index1]) + (rectWidth / 2)) + ',' + yScale(data[index1].value) + ')')
						}



					}



				}

				function getData(num) {

					var unitData = contentW / xScaleData.length,
						preIndex,
						nextIndex, currentIndex, k,
						vaildIndex, y, currentValue, vaildValue, x, b


					var currentIndex = Math.floor(num / unitData)

					if (currentIndex < 0) {

						currentIndex = 0
					}

					if (currentIndex > xScaleData.length - 1) {

						currentIndex = xScaleData.length - 1
					}
					preIndex = currentIndex - 1

					nextIndex = currentIndex + 1

					if ((num / unitData) - currentIndex >= 0.5) {

						vaildIndex = nextIndex

					} else {

						vaildIndex = preIndex
					}

					if (vaildIndex <= -1 || vaildIndex >= xScaleData.length - 1) {

						vaildIndex = currentIndex
					}

					currentValue = yScale(data[currentIndex].value[1])

					vaildValue = yScale(data[vaildIndex].value[1])

					if (currentIndex >= vaildIndex) {

						x = num - (currentIndex * unitData) + translate

						k = -1

						b = vaildValue
					} else {

						x = num - (currentIndex * unitData) - translate


						k = 1

						b = currentValue
					}
					y = k * (vaildValue - currentValue) * x / unitData + b

					return [currentIndex, y]
				}

			})
		}

	}

	return {
		rectChart: rectChart
	}

})